<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<!-- dom -->
		<span tip-msg='原生js 实现对未来动态增加的元素进行事件绑定'>鼠标悬停</span>

		<script type="text/javascript">
			function view() {
				console.log("鼠标移入")
			}

			/* document.querySelector("*[tip-msg]").addEventListener('mouseover', function(e) {
				let _this = e.target;
				//显示tip组件
				document.getElementById("tipBox").style.display = "block";
				let tipBody = document.getElementById("tipBody");
				tipBody.innerHTML = e.target.getAttribute("tip-msg");
			}) */

			//初始化组件
			var Tips = {
				title: "提示",
				box: null,
				header: null,
				body: null,
				init: function() {
					//防止重复构建
					if (this.box == null) {
						this._box();
						this.header = this._header();
						this.box.appendChild(this.header);
						this.body = this._body();
						this.box.appendChild(this.body);
						//将组件挂载到body
						document.body.appendChild(this.box);
						console.info("Tips构建完毕");
						this._startListener();
						console.info("Tips开始监听目标元素")
					}
				},
				/**
				 * 初始化容器
				 */
				_box: function() {
					this.box = document.createElement("div");
					this.box.setAttribute("id", "tipBox")
					this.box.style.cssText =
						"display: none;z-index:9999;border-color: rgb(0, 0, 0);position: fixed;color:#fff;font-family: 微软雅黑;border: 1px solid #CCCCCC;padding: 5px;box-shadow: rgb(0 0 0 / 20%) 1px 1px 2px; border-radius: 5px;background-color: rgba(0, 0, 0, 0.498); transition: left 0.4s ease 0s, top 0.4s ease 0s";
				},
				_header: function() {
					let head = document.createElement("div");
					head.setAttribute("id", "tipHeader");
					head.style.cssText = "line-height: 18px;height:20px;font-size: 16px;";
					head.innerHTML = this.title;
					return head;
				},
				_body: function() {
					let tipBody = document.createElement("tipBody");
					tipBody.setAttribute("id", "tipBody");
					tipBody.style.cssText = "font-size: 12px;";
					return tipBody;
				},
				/**
				 * 显示提示框
				 * @param {Object} msg	提示语
				 * @param {Object} top  目标位置y轴
				 * @param {Object} left 目标位置x轴
				 */
				_show: function(title,msg, top, left) {
					if(!title){
						this.header.style.display = "none";
					}else{
						this.header.innerHTML = title;
					}
					this.body.innerHTML = msg;
					if (this.box.style.display == "none") {
						this.box.style.display = "block";
					}
					this.box.style.top = top + "px";
					this.box.style.left = left + "px";
				},
				_close: function() {
					this.box.style.display = "none";
				},
				_startListener: function() {
					let parent = this;
					document.querySelector("*").addEventListener('mouseover', function(e) {
						let _this = e.target;
						console.log(e)
						let tipMsg = _this.getAttribute("tip-msg");
						if (tipMsg) {
							parent._show(null,tipMsg, e.y, e.x);
						} else {
							parent._close();
						}
					})
					console.info("启动监听器")
				}
			}

			Tips.init();
		</script>
</html>
